/**
 * Copyright ? 2006 DMX Technologies Corporation.  All rights reserved.
 * COPYRIGHT NOTICE:  The existence of a copyright notice on Software
 * will not be construed as an admission or presumption that public disclosure
 * of Software or any trade secrets associated with Software has occurred
 * or is permitted.
 ********************************************************************
 * PROPRIETARY NOTICE:  The source code contained in this listing is a
 * proprietary confidential trade secret of DMX Technologies Corporation.
 * Unauthorized copying, adaptation, distribution, use, or display is prohibited.
 */

package com.dmx.fw.component.commonquery;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.context.support.ServletContextResourcePatternResolver;

import com.dmx.fw.bean.ColumnInfoBean;
import com.dmx.fw.bean.QueryInfoBean;
import com.dmx.fw.resource.SystemProperties;

/** 
 * @Description: 通用查询组件解析配置xml文件类
 * @author: system
 * @date: 2006
 * @version V1.0 
 * 
 */
public class QueryScriptDef {
	
	private final static Logger log = Logger.getLogger(QueryScriptDef.class);
	
	/** 
	 * @Fields _querySciptMap: 查询脚本缓存Map，缓存解析时生成的QueryInfoBean
	 */
	private static HashMap _querySciptMap = null;  //new HashMap<String,QueryInfoBean>();
	
	/**
	 * 初始化数据库查询script
	 */
	public void init(){
		if(_querySciptMap==null){
            synchronized (QueryScriptDef.class){
                _querySciptMap=getQueryInfoBeanInfo();
            }
        }
	}
	
	/** 
	* @Description: get QueryInfoBean by busiId 
	* @param busiId  
	* @return QueryInfoBean
	*/
	public static QueryInfoBean getQueryInfo(String busiId){
        if(_querySciptMap==null){
            synchronized (QueryScriptDef.class){
                _querySciptMap=getQueryInfoBeanInfo();
            }
        }
		return (QueryInfoBean)_querySciptMap.get(busiId);
		
	}
	
	/** 
	* @Description: get _querySciptMap From InputStream
	* @return HashMap
	*/
    public static HashMap getQueryInfoBeanInfo() {
        HashMap infoMap = new HashMap();
        try {
        	
    		PathMatchingResourcePatternResolver pp = new PathMatchingResourcePatternResolver();
//    		Resource[] recs = pp.getResources("/WEB-INF/query/query*.xml");
    		
    		String configUrl = "classpath*:/springconfig/applicationContext_query/query_oracle/app-query-*.xml";
    		if(SystemProperties.getInstance().getCurrentDataBase().equals("mysql")){
    			configUrl = "classpath*:/springconfig/applicationContext_query/query_mysql/app-query-*.xml";
    		}
    		
    		Resource[] recs = pp.getResources(configUrl);
                for (int i = 0;i < recs.length;i++) {
                    parseQueryInfoBeansFromXML(recs[i].getInputStream(), infoMap);
                }
        } catch (Exception ex) {
        	ex.printStackTrace();
            //log.error(ex);
        }
        return infoMap;

    }

    /**
     * @Description: 解析配置文件，读取相关的查询信息
     * 
     * @param is: 
     *            查询配置文件输入流
     * @param map: 
     *            查询配置信息
     */
    private static void parseQueryInfoBeansFromXML(InputStream is, HashMap map) {
        try {
            SAXReader builder = new SAXReader();
            Document doc = builder.read(is);
            List queryList = doc.getRootElement().selectNodes("query");
            Iterator queryIt = queryList.iterator();
            while (queryIt.hasNext()) {
                Element queryE = (Element) queryIt.next();
                QueryInfoBean bean = getQueryInfoBeanByNode(queryE);
                if (bean!=null){
                	map.put(bean.getQueryID(), bean);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex);
        }
    }

    /**
     * @Description: 解析query 节点，取得一查询信息
     * @param queryElement: query element
     * @return QueryInfoBean
     */
    private static QueryInfoBean getQueryInfoBeanByNode(Element queryElement) {
    	QueryInfoBean bean = null;
    	try{
	        String id = queryElement.attributeValue("busiId");
	
	        String queryDesc = null;
	        Element queryDescE = (Element) queryElement.selectSingleNode("query-desc");
	        
	        if (queryDescE!=null){
	        	queryDesc = queryDescE.getTextTrim();
	        }
	        if (queryDesc==null){
	        	queryDesc = "";
	        }
	        Element sqlE = (Element) queryElement.selectSingleNode("sql");
	        String sql = sqlE.getText();
	        
	        String orderby = null;
	        Node orderbyE = queryElement.selectSingleNode("orderby");
	        if (orderbyE!=null){
	        	orderby = orderbyE.getText();
	        }
	        if (orderby==null)
	        	orderby = "";
	        HashMap paramMap = new HashMap();
	        List paramList = queryElement.selectNodes("params/param");
	        if (paramList!=null){
		        Iterator paramIt = paramList.iterator();
		        while (paramIt.hasNext()) {
		            Element paramE = (Element) paramIt.next();
		            String name = paramE.attributeValue("name");
		            String where = paramE.attributeValue("value");
		            String value = paramE.getText();
		            if(where!=null){
		            	Map whereMap=null;
			            if(paramMap.containsKey(name)){
			            	Object val=paramMap.get(name);
			            	if(Map.class.isAssignableFrom(val.getClass())){
			            		whereMap=(Map)val;
			            	}else{
			            		whereMap=new HashMap();
			            		whereMap.put(name,val);
			            	}
			            }
			            if(whereMap==null) whereMap=new HashMap();
			            whereMap.put(where, value);
		            	paramMap.put(name, whereMap);	
		            }else{
			            paramMap.put(name, value);
		            }
		        }
	        }
	        
	        List columnList = new ArrayList();
	        List tmpColumnList = queryElement.selectNodes("columns/column");
	        
	        if (tmpColumnList!=null){
		        Iterator columnIt = tmpColumnList.iterator();
		        while (columnIt.hasNext()) {
		            Element columnE = (Element) columnIt.next();
		            String columnName = columnE.attributeValue("name");
  
		            if(columnName!=null){
			            ColumnInfoBean columnInfoBean = new ColumnInfoBean();
			            columnInfoBean.setName(columnName);
			            columnInfoBean.setShow(true);
			            columnInfoBean.setExport(true);
			            
			            String isShow = columnE.attributeValue("show");
			            String isExport = columnE.attributeValue("export");
			            String prefix = columnE.attributeValue("prefix");
			            String align = columnE.attributeValue("align");
			            String type = columnE.attributeValue("type");
			            if (align==null){
			            	align = "center";
			            	
			            }
			            
			            if (type==null){
			            	type = "string";
			            	
			            }  
			            
			            columnInfoBean.setAlign(align);
			            columnInfoBean.setType(type);
			            
			            if (prefix==null){
			            	prefix = "";
			            }
			            columnInfoBean.setPrefix(prefix);
			            if (isShow!=null && "0".equals(isShow)){
			            	columnInfoBean.setShow(false);
			            }
			            if (isExport!=null && "0".equals(isExport)){
			            	columnInfoBean.setExport(false);
			            }
			            
			            columnInfoBean.setTitle(columnE.getText());
			            columnList.add(columnInfoBean);
		            }
		        }
	        }
	        
	        bean = new QueryInfoBean();
	        bean.setQueryID(id);
	        bean.setQueryDescription(queryDesc);
	        bean.setQueryScript(sql);
	        bean.setOrderByScript(orderby);
	        bean.setConditionsMap(paramMap);
	        bean.setColumnList(columnList);
    	}catch(Exception e){
    		log.error(e);
    	}
        return bean;

    }
	
}
